<?php

class AccountsController extends AppController {

    var $name = 'Accounts';
    var $helpers = array('Html', 'GoogleChart');

    function index() {
        $this->Account->recursive = 0;
        $this->set('accounts', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid account', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('account', $this->Account->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->Account->create();
            if ($this->Account->save($this->data)) {
                $this->Session->setFlash(__('The account has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The account could not be saved. Please, try again.', true));
            }
        }
        $users = $this->Account->User->find('list');
        $this->set(compact('users'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid account', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Account->save($this->data)) {
                $this->Session->setFlash(__('The account has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The account could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Account->read(null, $id);
        }
        $users = $this->Account->User->find('list');
        $this->set(compact('users'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for account', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Account->delete($id)) {
            $this->Session->setFlash(__('Account deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Account was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function review($account_id = null) {
        
        //might be better to use $this->Session->check('User') here...
        
        global $user;
        $u = $user;
		
        $params = array(
            'conditions' => array('User.id' => $u['User']['id']),
            'fields' => array('Account.*'),
            'recursive' => 0
        );
        
        $this->set('accountList',$this->Account->find('list',array('conditions' => array('Account.user_id' => $u['User']['id']))));       

        if (!$account_id) {
            $accounts = $this->Account->find('all', $params);
        } else {
            $params['conditions']['Account.id'] = $account_id;
            $accounts[] = $this->Account->find('first', $params);
        }

        // debug($accounts);

        $today = new DateTime();

        $dateInterval = new DateInterval('P14D');
        $plus2weeks = new DateTime();
        $plus2weeks->add($dateInterval);

        $minus2weeks = new DateTime();
        $minus2weeks->sub($dateInterval);

        $oneDayStep = new DateInterval('P1D');

        // build 4 wk calendar
        $calendar = array();
        $entryDate = $minus2weeks;
        while (($entryDate->getTimestamp() <= $plus2weeks->getTimestamp())) {
            $calendar[$entryDate->format('Y-m-d')] = array();
            $entryDate->add($oneDayStep);
        }

        foreach ($accounts as $key => $account) {
            $acctId = $account['Account']['id'];
            //
            // get most recent total
            //                
            $accountTotalData = $this->Account->Total->getRecentTotal($acctId);
            $account['Total'] = $accountTotalData['Total'];
            $benchmarkPostDate = $account['Total']['post_date'];

            //
            // forcast through today+2wks
            //                
            $this->Account->forecast($acctId, $plus2weeks->format('Y-m-d'));


            // create an array with day-by-day transactions
            // starting from -2wks through +2wks
            foreach ($calendar as $day => $empty) {
                $account['History'][$day] = $this->Account->Transaction->getTransactionsByDate($day, $acctId);
            }

            // compute running total from history
            // start at a recent total's post_date
            $benchmark = new DateTime($benchmarkPostDate);

            //  
            //  if not query all transactions since then, add it our window
            //  

            if (!array_key_exists($benchmarkPostDate, $account['History'])) {
                // Get transactions between post date and left-window

                $windowMin = array_shift(array_keys(array_slice($account['History'], 1, 1)));

                // get transactions by dates since benchmark total
                $pastTransactions = $this->Account->Transaction->getTransactionsByTimeFrame($benchmarkPostDate, $windowMin, $acctId);
                array_pop($pastTransactions);

                $account['History'] = array_merge($account['History'], $pastTransactions);

                ksort($account['History']);
            }

            // calculate running total from benchmark left
            $leftMostDate = array_shift(array_keys(array_slice($account['History'], 1, 1)));
            $left = new DateTime($leftMostDate);

            $right = new DateTime($benchmarkPostDate);

            $runningTotal = $account['Total']['balance'];

            while ($right->getTimestamp() >= $left->getTimeStamp()) {
                $date = $right->format('Y-m-d');
                $thisDaysTotal = 0;
                foreach ($account['History'][$date] as $t) {
                    $thisDaysTotal -= $t['Transaction']['amount'];
                }
                $runningTotal += $thisDaysTotal;

                $account['Balances'][$date] = array(
                    'date' => $date,
                    'daily' => $thisDaysTotal,
                    'total' => $runningTotal
                );
                $right->sub($oneDayStep);
            }


            // calculate running total from from benchmark right
            $rightMostDate = array_shift(array_keys(array_slice($account['History'], -1, 1)));
            $right = new DateTime($rightMostDate);

            $left = new DateTime($benchmarkPostDate);

            $runningTotal = $account['Total']['balance'];

            while ($left->getTimestamp() <= $right->getTimeStamp()) {
                $date = $left->format('Y-m-d');
                $thisDaysTotal = 0;
                foreach ($account['History'][$date] as $t) {
                    $thisDaysTotal += $t['Transaction']['amount'];
                }
                $runningTotal += $thisDaysTotal;

                $account['Balances'][$date] = array(
                    'date' => $date,
                    'daily' => $thisDaysTotal,
                    'total' => $runningTotal
                );
                $left->add($oneDayStep);
            }

            $accounts[$key] = $account;
        }
        $this->set('accounts', $accounts);
    }

}
